﻿using Microsoft.AspNetCore.Http.Features;
using Framework.EncryptionService;
using Framework.EncryptionService.Attributes;

namespace Bright.NetCore.Api.Middleware
{
    /// <summary>
    /// 入参解密中间件
    /// </summary>
    public class InputDecryptionMiddleware
    {
        private readonly RequestDelegate _next;

        /// <summary>
        /// 入参解密中间件
        /// </summary>
        /// <param name="next"></param>
        public InputDecryptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 入参解密
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task InvokeAsync(HttpContext context)
        {
            //获取接口特性
            var endpointFeature = context.Features.Get<IEndpointFeature>()?.Endpoint?.Metadata?.GetMetadata<NonEncryptedAttribute>();
            //入参解密
            var data = InputDecryption.InputDecryptionHelps(context, endpointFeature);
            //添加前端AES秘钥到会话中
            if (!string.IsNullOrWhiteSpace(data.AesSecret)) context.Session.SetString("AesSecret", data.AesSecret);

            if (context.Request.ContentType != "application/json")
            {
                context.Request.ContentType = "application/json";
            }
            if (data.Body != null) context.Request.Body = data.Body;

            if (data.Code != 0)
            {
                context.Response.StatusCode = data.Code;
                await context.Response.WriteAsync(data.Message);
            }
            // 调用下一个中间件
            await _next(context);
        }
    }
}
